﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Configuration;

namespace SelArom.Net.Sitefinity.Helpers
{
	public static class CacheHelper
	{
		private static Object FileLock = new Object();
		private static HttpServerUtility Server = HttpContext.Current.Server;

		/// <summary>
		/// Clears the file cache
		/// </summary>
		public static void Clear(string Path)
		{
			lock (FileLock)
			{
				var dir = new DirectoryInfo(Server.MapPath(Path));
				if (dir.Exists)
					foreach (var file in dir.GetFiles())
						file.Delete();
			}
		}

		public static void Delete(string filename)
		{
			lock (FileLock)
			{
				var path = Server.MapPath(filename);
				if (File.Exists(path)) File.Delete(path);
			}
		}

		public static string ReadFile(FileInfo file)
		{
			if (file == null) return string.Empty;
			string retval;

			// allow only one creator
			lock (FileLock)
			{
				if (!file.Exists)
				{
					try
					{
						file.Create().Close();
					}
					catch (DirectoryNotFoundException)
					{
						// this should never happen
						if (string.IsNullOrEmpty(file.DirectoryName)) throw new NullReferenceException("File Directory cannot be blank");

						Directory.CreateDirectory(file.DirectoryName);
						file.Create().Close();
					}
					finally
					{
						// reload the file
						file = new FileInfo(file.FullName);
					}
				}

				// make sure cache is available and valid
				retval = file.Length == 0 ? string.Empty : File.ReadAllText(file.FullName);

			}
			return retval;
		}

		public static string ReadFile(FileInfo file, TimeSpan TimeToCache)
		{
			if (file == null) return string.Empty;
			string retval;

			// allow only one creator
			lock (FileLock)
			{
				if (!file.Exists)
				{
					try
					{
						file.Create().Close();
					}
					catch (DirectoryNotFoundException)
					{
						// this should never happen
						if (string.IsNullOrEmpty(file.DirectoryName)) throw new NullReferenceException("File Directory cannot be blank");

						Directory.CreateDirectory(file.DirectoryName);
						file.Create().Close();
					}
					finally
					{
						// reload the file
						file = new FileInfo(file.FullName);
					}
				}

				// make sure cache is available and valid
				retval = file.Length == 0 || file.LastWriteTime + TimeToCache < DateTime.Now ? string.Empty : File.ReadAllText(file.FullName);

			}
			return retval;
		}

		public static void WriteFile(string filename, string data)
		{
			lock (FileLock)
			{
				File.WriteAllText(filename, data);
			}
		}
	}
}